package com.newway.back.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newway.back.entity.SysUserEntity;
import com.newway.back.mapper.SysMenuMapper;
import com.newway.back.entity.SysMenuEntity;
import com.newway.back.service.SysMenuService;
import com.newway.back.util.SecurityUserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenuEntity> implements SysMenuService {

    @Autowired
    SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenuEntity> selectMenuById(int i) {
        SysUserEntity currentUserInfo = SecurityUserContext.getCurrentUserInfo();
        List<SysMenuEntity> list;
        if(1==currentUserInfo.getId()){
            list = sysMenuMapper.selectList(null);
        }else{
            list = sysMenuMapper.selectMenuByUserId(currentUserInfo.getId());
        }
        list = list.stream().filter(each->!each.getType().equals("2")).collect(Collectors.toList());
        List<SysMenuEntity> parents = list.stream().filter(e->e.getParentId().equals("0") ).collect(Collectors.toList());
        getChilds(parents,list);
        return parents;
    }

    /**
     * 将结果转化为树形结构
     * @param parents
     * @param list
     */
    private void getChilds(List<SysMenuEntity> parents, List<SysMenuEntity> list) {
        parents.forEach(item->{
            List<SysMenuEntity> collect = list.stream().filter(e->e.getParentId().equals(item.getId().toString())).collect(Collectors.toList());
            item.setChildren(collect);
            if(!collect.isEmpty()) {
                getChilds(collect,list);
            }
        });
    }
}
